﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseInspcombinesetting;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：检验批合并设置.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Inspcombinesetting", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseInspCombineSettingService : IQmsBaseInspcombinesettingService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseInspcombinesettingEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseInspcombinesettingService"/>类型的新实例.
    /// </summary>
    public QmsBaseInspCombineSettingService(
        ISqlSugarRepository<QmsBaseInspcombinesettingEntity> qmsBaseInspcombinesettingRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseInspcombinesettingRepository;
        _dataInterfaceService = dataInterfaceService;
        _db = context.AsTenant();
        _userManager = userManager;
    }

    /// <summary>
    /// 获取检验批合并设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        var res = (await _repository.Context.Queryable<QmsBaseInspcombinesettingEntity, UserEntity, UserEntity>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.CreatorUserId == b.Id, JoinType.Left, a.LastModifyUserId == c.Id))
            .Select((a, b, c) => new QmsBaseInspcombinesettingEntity
            {
                Id = a.Id,
                Type = a.Type,
                MergeConditions = a.MergeConditions,
                MergeConditionsName = a.MergeConditionsName,
                CreatorUserId = b.RealName,
                CreatorTime = a.CreatorTime,
                LastModifyUserId = c.RealName,
                LastModifyTime = a.LastModifyTime,
                EnabledMark = a.EnabledMark,
                //EnabledMarkDesc = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常")
            }).FirstAsync(a => a.Id.Equals(id))).Adapt<QmsBaseInspcombinesettingInfoOutput>();

        return res;
    }

    /// <summary>
    /// 获取检验批合并设置列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseInspcombinesettingListQueryInput input)
    {
        var mergeConditions = input.mergeConditions?.Split(',').ToList().Last();
        var queryable = _repository.Context.Queryable<QmsBaseInspcombinesettingEntity>()
            .InnerJoin<DictionaryDataEntity>((a, b) => b.DictionaryTypeId.Equals("448687444825473541") && a.Type == b.EnCode && b.DeleteMark == null && b.EnabledMark == 1)
            .Where(a => a.DeleteMark == null)
            .WhereIF(!string.IsNullOrEmpty(input.type), a => a.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.mergeConditions), a => a.MergeConditions.Contains(mergeConditions))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.Type.Contains(input.keyword) || a.MergeConditions.Contains(input.keyword))
            .Select((a, b) => new QmsBaseInspcombinesettingListOutput
            {
                id = a.Id,
                type = b.FullName,
                mergeConditions = a.MergeConditions,
                mergeConditionsName = a.MergeConditionsName,
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBaseInspcombinesettingListOutput>.SqlSugarPageResult(data);

        //await _repository.Context.ThenMapperAsync(data.list, async item =>
        //{
        //    // 合并字段
        //    var mergeConditionsMergeConditions = item.mergeConditions.ToObject<List<string>>();
        //    item.mergeConditions = string.Join(",", await _repository.Context.Queryable<DictionaryDataEntity>().Where(it => mergeConditionsMergeConditions.Contains(it.EnCode) && it.DictionaryTypeId.Equals("453033691602491973")).Select(a => a.FullName).ToListAsync());

        //});
    }

    /// <summary>
    /// 新建检验批合并设置.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseInspcombinesettingCrInput input)
    {
        if (await _repository.AnyAsync(x => (x.Type == input.type) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<QmsBaseInspcombinesettingEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        entity.CreatorUserId = _userManager.UserId;
        entity.CreatorTime = DateTime.Now;
        var isOk = await _repository.Context.Insertable(entity)
            .IgnoreColumns(ignoreNullColumn: true)
            .CallEntityMethod(m => m.Creator())
            .ExecuteCommandAsync();

        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取检验批合并设置无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseInspcombinesettingListQueryInput input)
    {
        var mergeConditions = input.mergeConditions?.Split(',').ToList().Last();
        var list = await _repository.Context.Queryable<QmsBaseInspcombinesettingEntity>()
            .InnerJoin<DictionaryDataEntity>((a, b) => b.DictionaryTypeId.Equals("448687444825473541") && a.Type == b.EnCode && b.DeleteMark == null && b.EnabledMark == 1)
            .Where(a => a.DeleteMark == null)
            //.InnerJoin<DictionaryDataEntity>((a, b, c) => b.DictionaryTypeId.Equals("453033691602491973") && a.MergeConditions.Contains(b.EnCode) && b.DeleteMark == null && b.EnabledMark == 1)
            .WhereIF(!string.IsNullOrEmpty(input.type), a => a.Type.Equals(input.type))
            .WhereIF(!string.IsNullOrEmpty(input.mergeConditions), a => a.MergeConditions.Contains(mergeConditions))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.Type.Contains(input.keyword) || a.MergeConditions.Contains(input.keyword))
            .OrderByIF(!string.IsNullOrEmpty(input.sidx), a => input.sidx + " " + input.sort)
            .Select((a, b) => new QmsBaseInspcombinesettingListOutput
            {
                id = a.Id,
                type = b.FullName,
                mergeConditions = a.MergeConditions,
                mergeConditionsName = a.MergeConditionsName,
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
            }).ToListAsync();

        //await _repository.Context.ThenMapperAsync(list, async item =>
        //{
        //    // 合并字段
        //    var mergeConditionsMergeConditions = item.mergeConditions.ToObject<List<string>>();
        //    item.mergeConditions = string.Join(",", await _repository.Context.Queryable<DictionaryDataEntity>().Where(it => mergeConditionsMergeConditions.Contains(it.EnCode) && it.DictionaryTypeId.Equals("453033691602491973")).Select(a => a.FullName).ToListAsync());

        //});

        return list;
    }

    /// <summary>
    /// 导出检验批合并设置.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseInspcombinesettingListQueryInput input)
    {
        var exportData = new List<QmsBaseInspcombinesettingListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseInspcombinesettingListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"检验类型\",\"field\":\"type\"},{\"value\":\"合并条件\",\"field\":\"mergeConditionsName\"},{\"value\":\"合并条件编号\",\"field\":\"mergeConditions\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "业务合批规则.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseInspcombinesettingListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除检验批合并设置.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseInspcombinesettingEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除检验批合并设置
                await _repository.Context.Deleteable<QmsBaseInspcombinesettingEntity>().In(it => it.Id, ids).ExecuteCommandAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新检验批合并设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseInspcombinesettingUpInput input)
    {
        if (await _repository.AnyAsync(x => (x.Type == input.type) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<QmsBaseInspcombinesettingEntity>();
        entity.LastModifyUserId = _userManager.UserId;
        entity.LastModifyTime = DateTime.Now;
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.Type,
            it.MergeConditions,
            it.MergeConditionsName,
            it.LastModifyUserId,
            it.LastModifyTime,
            it.EnabledMark,
        }).CallEntityMethod(m => m.LastModify()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除检验批合并设置.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Deleteable<QmsBaseInspcombinesettingEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
    }
}